<?php


namespace app\api\controller\v20;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlFortuneUp;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\model\Recode;
use app\common\model\Recode as RecodeModel;
use think\Env;

/**
 * V2.3.0 商城
 * 本命报告
 * Class NatalReport
 * @package app\api\controller\v20
 */
class NatalReport extends Auth
{
    /**
     * 本命报告详情
     */
    public function detail()
    {
        $gid = input('gid/d', 0);
        if (!in_array($gid, [39, 40, 41, 42, 52], true))
        {
            return show(config('code.error'), '未知的商品');
        }
        $rid = input('rid/d', 0);
        if (!$rid && !$this->user['rid'])
        {
            return show(406, '档案缺失，去添加档案');
        }
        $rid = $rid ?: $this->user['rid'];

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $uid = $this->user['id'];
        $NatalReportModel = new \app\common\cachemodel\NatalReport();

        if (!$gid) return show(config('code.error'), '请求异常');

        //获取商品类型
        $goodData = (new NatalGoods())->getGoods();
        // 判断当前解锁状态
        $unlockReport = $NatalReportModel->getNatalReport2($recode);
        // $unlockReport = $NatalReportModel->getNatalReport($uid, $rid);

        if ($unlockReport && isset($unlockReport[$gid]) && $unlockReport[$gid]['status'] == 2)
        {   // 解锁成功
            $gname = '';
            foreach ($goodData as $key => $item)
            {
                if ($item['id'] == $gid)
                {
                    $gname = $item['name'];
                    break;
                }
            }
            $result = [
                'status' => 2,
                'url' => Env::get('host.domain') . '/web/natal_report/index?gid=' . $gid . '&rid=' . $rid,
                'gname' => $gname
            ];
        } else
        {   // 未解锁 或 解锁中
            $orderModel = new \app\common\cachemodel\Orders();
            $status = isset($unlockReport[$gid]) ? ($unlockReport[$gid]['status'] == 2 ? 2 : 1) : 0;
            $unlockingData = [];
            $activeData = [];
            $lockData = [];
            $unlockData = [];
            $gname = '';
            $textNum = 0;
            $unlockNum = 0;
            $headerBg = '';
            $contentBg = '';
            $natalReportPrice = [];
            $activingModel = new ZhunleActivity();
            //获取报告商品图片
            $reportImage = ConfigManage::natalReportGoodImage(1);
            foreach ($goodData as $key => $item)
            {
                $unlockNumber = $orderModel->getTotalPrepaidOrder(7, $item['id']);
                // 获取活动商品信息
                $activing = $activingModel->getActivingGood(7, $item['id']);
                if ($activing)
                {
                    $actiGids = explode(',', $activing['gids']);
                    if (in_array($gid, $actiGids, false))
                    {
                        $discount_price = sprintf('%.2f', $item['now_prize'] * $activing['attr']);
                    }
                    $timeRange = $activing['end_time'] - time();
                }
                if ($item['id'] == $gid)
                {
                    $natalReportPrice = [
//                        'or_price' => $item['or_prize'],
                        'now_price' => $discount_price ?? $item['now_prize'],
                        'active_time' => $timeRange ?? 0,
                    ];
                    $gname = $item['name'];
                    $unlockNum = $item['base_num'] + $unlockNumber;
                    $textNum = $item['text_num'];
                    $headerBg = $item['header_bg'];
                    $contentBg = $item['content_bg'];
                } else
                {
                    if ($item['status'] != 2)
                    {
                        if (isset($unlockReport[$item['id']]))
                        {
                            if ($unlockReport[$item['id']]['status'] == 2)
                            {
                                $unlock_status = 2;//已解锁
                            } else
                            {
                                $unlock_status = 1;//计算中
                            }
                        } else
                        {
                            $unlock_status = 0;//未解锁
                        }
                    } else
                    {
                        $unlock_status = 3;//未开放
                    }

                    $d = [
                        'gid' => (int)$item['id'],
                        'status' => $unlock_status,
                        'bg_img' => $reportImage['large'][$item['flag']] ?? '',
                        'gcolor' => $item['color'] ?? '',
                        'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                        'unlock_num' => $item['base_num'] + $unlockNumber,
                        'active_time' => $timeRange ?? 0,
                    ];

                    if ($d['status'] == 1)
                    {   // 解锁中
                        $unlockingData[] = $d;
                    } elseif ($d['status'] == 0)
                    {   // 未解锁
                        $lockData[] = $d;
                    } elseif ($d['status'] == 2)
                    {   // 已解锁
                        $unlockData[] = $d;
                    }
                }
            }

            $result = [
                'gname' => $gname,
                'status' => (int)$status,
                'text_num' => (int)$textNum,
                'unlock_num' => (int)$unlockNum,
                'header_bg' => $headerBg,
                'content_bg' => $contentBg,
                'natal_report_list' => array_merge($activeData, $unlockData, $unlockingData, $lockData),
                'natal_report_price' => $natalReportPrice
            ];
        }

        return show(config('code.success'), '请求成功', $result);
    }

    /**
     * 获取不同运势的信息 v2.4.1厄运消除  去除之前版本厄运消除数据结构
     * @throws ApiException
     * @throws \Exception
     */
    public function multipleFortune()
    {
        $type = input('type/d', 0);
        $in_sign = input('in_sign/d', 1);
        $fortuneModel = new Fortune();
        switch ($type)
        {
            case 1:
                $data = $fortuneModel->todayInfoV2($this->user);
                // 获取运势提升状态 1已提升 0未提升
                $isFortuneUp = (new ZlFortuneUp())->getFortuneUpStatus((int)$this->user['rid'], (int)(date('Ymd')));
                if ($isFortuneUp)
                {
                    $data['today']['fortune_up_status'] = 2;
                } else
                {
                    $data['today']['fortune_up_status'] = 0;
                    foreach ($data['today']['list'] as $item)
                    {
                        if (in_array($item['color'], ['#ffed17', '#ffa536', '#7775ff'], true))
                        {
                            $data['today']['fortune_up_status'] = 1;
                            break;
                        }
                    }
                }
                break;
            case 2:
                if ($this->user && $this->user['rid'])
                {
                    $map = ['uid' => $this->user['id'], 'isself' => 1];
                    $recode_info = (new RecodeModel())->getSelfRecode($map);

                    if (!$recode_info || !$recode_info['sun'])
                    {
                        return show(406, '档案缺失请添加档案');
                    }
                    $in_sign = explode('-', $recode_info['sun'])[0];
                } elseif (!in_array($in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
                {
                    return show(408, '请选择星座');
                }
                $data = $fortuneModel->weekInfo($in_sign);
                break;
            case 3:
                $data = $fortuneModel->monthInfo($this->user, $this->headers['version']);
                break;
            case 4:
                $data = $fortuneModel->yearInfo($this->user, $this->headers['version']);
                break;
            case 5:
                $data = $fortuneModel->reportInfo($this->user);
                break;
            default:
                $data = [];
                break;
        }
        if ($data)
        {
            return show(config('code.success'), '获取成功', $data);
        }
        return show(config('code.error'), '未知的运势');
    }
}
